package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.album.TrackStatVo;
import com.atguigu.tingshu.vo.user.LastUserListenPlayVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private RedisTemplate redisTemplate;
    @Autowired
    private KafkaService kafkaService;

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo) {
		//获取当前登录的用户id
		Long userId = AuthContextHolder.getUserId();
		//拼接集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//根据用户的id和声音id从mongdb对应的集合中查询声音的播放进度数据
		Query query = Query.query(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId()));
		UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class,collectionName);
				//如果可以查询到数据执行更新操作
		if(listenProcess!=null){
			listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			listenProcess.setCreateTime(new Date());
			mongoTemplate.save(listenProcess,collectionName);
		}else {		//如果查询不到数据库执行新增操作
			listenProcess = new UserListenProcess();
			listenProcess.setUserId(userId);
			listenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			listenProcess.setTrackId(userListenProcessVo.getTrackId());
			listenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			listenProcess.setCreateTime(new Date());
			listenProcess.setUpdateTime(new Date());
			mongoTemplate.save(listenProcess,collectionName);
		}
		//查询Redis，判断当前的声音的播放量当前是否记录
		String redisKey = "track:play:"+userId+":"+userListenProcessVo.getTrackId()+":"+ DateUtil.format(new Date(),"yyyy-MM-dd");
		Boolean ifAbsent = redisTemplate.hasKey(redisKey);
		if (!ifAbsent){
			//向kafka中发送消息
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-",""));
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			kafkaService.sendMsg(KafkaConstant.QUEUE_TRACK_STAT_UPDATE,JSON.toJSONString(trackStatMqVo));
			//在Redis记录播放量的记录标识
			redisTemplate.opsForValue().set(redisKey, JSON.toJSONString(trackStatMqVo),1, TimeUnit.DAYS);
		}
	}

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId) {
		//获取当前登录的用户id
		Long userId = AuthContextHolder.getUserId();
		//拼接集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//根据用户的id和声音id从mongdb对应的集合中查询声音的播放进度数据
		Query query = Query.query(Criteria.where("userId").is(userId).and("trackId").is(trackId));
		UserListenProcess listenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		if (listenProcess==null){
			return new BigDecimal(0);
		}else {
			return listenProcess.getBreakSecond();
		}
	}

	@Override
	public LastUserListenPlayVo getLatelyTrack() {
		//获取当前登录用户的id
		Long userId = AuthContextHolder.getUserId();
		//拼接集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//根据用户id查询最后一次声音的播放信息
		Query query = Query.query(Criteria.where("userId").is(userId));
		query.with(Sort.by(Sort.Direction.DESC,"UpdateTime"))
			 .limit(1);
		//从mongodb中获取一个符合条件的声音
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//将查询到的结果数据封装
		LastUserListenPlayVo lastUserListenPlayVo = new LastUserListenPlayVo();
		lastUserListenPlayVo.setAlbumId(userListenProcess.getAlbumId());
		lastUserListenPlayVo.setTrackId(userListenProcess.getTrackId());
		//返回结果
		return lastUserListenPlayVo;
	}

}
